package cn.edu.scnu.thewonderofink.logic

import androidx.lifecycle.liveData
import cn.edu.scnu.thewonderofink.logic.network.RecognitionNetwork
import kotlinx.coroutines.Dispatchers
import org.json.JSONObject
import kotlin.coroutines.CoroutineContext

object Repository {

    private var judge = true

    fun getResponse(image: String) = fire(Dispatchers.IO) {
        // 将数据转换为JSON字符串
        val data = JSONObject()
            .put("image", image)
            .toString()
        // 发送数据
        RecognitionNetwork.sendImage(data)
        // 初次使用，延迟进程
        if (judge){
            Thread.sleep(1500)
            judge = false
        }
        else
            Thread.sleep(500)
        // 获取返回值
        val response = RecognitionNetwork.getResponse()
        if (response.code == "200") {
            Result.success(response)
        } else {
            Result.failure(RuntimeException("response status is ${response.code}"))
        }
    }


    private fun <T> fire(context: CoroutineContext, block: suspend () -> Result<T>) =
        liveData(context) {
            val result = try {
                block()
            } catch (e: Exception) {
                Result.failure<T>(e)
            }
            emit(result)
        }

}